package com.loop.niochat;

import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * 群聊 客户端
 *
 * @author zhangxiaolu
 * @since 2023-09-05 22:52
 */
public class GroupChatClient {

    // 定义相关属性
    private final String HOST = "127.0.0.1";// 服务器IP
    private final int PORT = 6667;// 服务器端口
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    // 构造器，完成初始化
    public GroupChatClient() {
        try {
            selector = Selector.open();
            // 连接服务器
            socketChannel = SocketChannel.open(new java.net.InetSocketAddress(HOST, PORT));
            // 设置为非阻塞
            socketChannel.configureBlocking(false);
            // 将通道注册到选择器
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 得到username
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + " is ok");
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 向服务器发送消息
    public void sendInfo(String msg) {
        msg = username + " 说：" + msg;
        try {
//            socketChannel.write(StandardCharsets.UTF_8.encode(CharBuffer.wrap(msg)));
            socketChannel.write(ByteBuffer.wrap(msg.getBytes()));
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    // 读取从服务端返回的消息
    public void readInfo() {
        try {
            int readChannels = selector.select();
            // 如果有可用的通道
            if (readChannels > 0) {
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()) {
                    SelectionKey key = iterator.next();
                    if (key.isReadable()) {
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer);
//                        String msg = StandardCharsets.UTF_8.decode(buffer).toString();
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                    }
                }
                iterator.remove(); // 防止重复操作
            }/* else
                System.out.println("没有可用的通道");*/
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public static void main(String[] args) {
        // 启动我们的客户端
        GroupChatClient chatClient = new GroupChatClient();
        new Thread(() -> {
            chatClient.readInfo();
            try {
                // 睡3秒
                Thread.sleep(3000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        // 发送数据给服务端
        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()) {
            String s = scanner.nextLine();
            chatClient.sendInfo(s);
        }
    }
}
